package webService;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import serverDB.Client;
import serverDB.ConnectToDataBase;
import serverManger.Server;
/**
 * creat new account
 * @author ran,barak
 *
 */
public class CreateAccountServlet extends HttpServlet{
	/**
	 * Default serialVersionUID
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * get the post request
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// if the account was created
		if(createAccount(req, resp,true))
			resp.sendRedirect("logedIn.jsp");
		else
			resp.sendRedirect("createAccount.jsp");		
	}
	
	/**
	 * get the Get requests
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// get the output stream
		ObjectOutputStream outputStream = new ObjectOutputStream(resp.getOutputStream());
		// if the client was created
		if(createAccount(req, resp,false))
			outputStream.writeObject(true);
		else
			outputStream.writeObject(false);
		outputStream.close();
	}
	
	/**
	 * create the account
	 * @param req the HttpServletRequest
	 * @param resp the HttpServletResponse
	 * @param flag if its from the website or not
	 * @return
	 */
	private boolean createAccount(HttpServletRequest req, HttpServletResponse resp, boolean flag){
		// get the session
		HttpSession session = req.getSession();
		ConnectToDataBase connectToDataBase = ConnectToDataBase.getInst();
		// get the client
		List<Client> list=connectToDataBase.getClient2("from Client where user_name= '"+req.getParameter("userName")+"'");
		if(list!=null&&flag){
			System.out.println("client Exist");
			session.setAttribute("error", "user name is not avaliable");
			return false;
		}
		else{
			Server server = Server.getServerInst();
			// new Computer
			if("null".equals(req.getParameter("boxName")))
				server.addNewClient(req.getParameter("userName"), req.getParameter("pass"), req.getParameter("email"), req.getParameter("compName"), req.getParameter("path"), null);
			// new client
			else
				server.addNewClient(req.getParameter("userName"), req.getParameter("pass"), req.getParameter("email"), req.getParameter("compName"), req.getParameter("path"), req.getParameter("boxName"));
			// set the attribute for the website
			session.setAttribute("logedIn", true);
			session.setAttribute("userName", req.getParameter("userName"));
			return true;
		}
	}
}
